#!/bin/bash

# 启动Web服务器脚本

# 检查是否提供了虚拟环境路径参数
if [ -z "$1" ]; then
    echo "使用方法: ./start_server.sh [虚拟环境路径] [可选:端口号，默认8188]"
    echo "示例: ./start_server.sh ./pywebcam_venv 8188"
    exit 1
fi

VENV_PATH=$1
PORT=${2:-8188}

# 检查虚拟环境是否存在，如果不存在则创建
if [ ! -d "$VENV_PATH" ]; then
    echo "📁 创建虚拟环境..."
    python3 -m venv "$VENV_PATH"
fi

# 激活虚拟环境
if [ -f "$VENV_PATH/bin/activate" ]; then
    source "$VENV_PATH/bin/activate"
    echo "✅ 已激活虚拟环境"
elif [ -f "$VENV_PATH/Scripts/activate" ]; then
    source "$VENV_PATH/Scripts/activate"
    echo "✅ 已激活虚拟环境"
else
    echo "❌ 未找到虚拟环境激活脚本"
    exit 1
fi

# 检查依赖
echo "🔍 检查依赖..."
pip install -r requirements.txt

# 检查OpenCV是否安装
echo "🔍 检查OpenCV安装..."
python -c "import cv2" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "⚠️  OpenCV未安装，正在安装..."
    pip install opencv-python-headless
fi

# 检查MQTT库是否安装
echo "🔍 检查MQTT库安装..."
python -c "import paho.mqtt.client" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "⚠️  MQTT库未安装，正在安装..."
    pip install paho-mqtt
fi

# 启动服务
echo "🚀 启动Web服务器，端口: $PORT"
python web_subscriber.py

echo "✅ 服务器已启动"